#!/usr/bin/env python
# encoding: utf-8
"""
main.py

Copyright (c) 2008 Patrick J Leyden III

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import cgi
import os
import wsgiref.handlers

from datastore import *
from converter import *

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import mail

class IndexPage(webapp.RequestHandler):
    def get(self):
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))


class ClubsPage(webapp.RequestHandler):
    def get(self):
        # TODO: add WHERE ower is myself
        clubs = db.GqlQuery('SELECT * FROM Club WHERE owner = :1 ORDER BY name',
                            users.get_current_user())
        
        template_values = {
            'my_clubs' : clubs
        }
        path = os.path.join(os.path.dirname(__file__), 'clubs.html')
        self.response.out.write(template.render(path, template_values))


class CreateClubPage(webapp.RequestHandler):
    def get(self):
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'create_club.html')
        self.response.out.write(template.render(path, template_values))
        
    def post(self):
        if cgi.escape(self.request.get('action')) == "Submit":
            new_club = Club(name = cgi.escape(self.request.get('name')),
                            owner = users.get_current_user(),
                            description = cgi.escape(self.request.get('description')))
            new_club.put()
        self.redirect('/clubs')
        
class ManageClubPage(webapp.RequestHandler):
    def post(self):
        key = cgi.escape(self.request.get('id'))
        club = db.get(key)
        members = []
        if len(club.members) > 0:
            members = db.get(club.members)
        template_values = {
            'club' : club,
            'members' : members
        }
        path = os.path.join(os.path.dirname(__file__), 'manage_club.html')
        self.response.out.write(template.render(path, template_values))
        
class EditMembersPage(webapp.RequestHandler):
    def post(self):
        key = cgi.escape(self.request.get('id'))
        club = db.get(key)
        sc = SimpleConverter()
        text = ""
        if len(club.members) > 0:
            text = sc.to_text(club.members)
        template_values = {
            'club' : club,
            'member_list_text' : text
        }
        path = os.path.join(os.path.dirname(__file__), 'edit_members.html')
        self.response.out.write(template.render(path, template_values))
    
class SaveMemberList(webapp.RequestHandler):
    def post(self):
        # TODO: make this redirect back to /manage_club with the correct
        #       club name.
        key = cgi.escape(self.request.get('id'))
        club = db.get(key)
        if cgi.escape(self.request.get('action')) == "Submit":
            member_list_text = cgi.escape(self.request.get('member_list_text'))
            sc = SimpleConverter()
            keys = sc.to_keys(member_list_text)
            # delete the old members first:
            if len(club.members) > 0:
                members = db.get(club.members)
                for member in members:
                    member.delete()
            # now assign the new keys and save.
            club.members = keys
            club.put()
        #self.redirect('/manage_club')
        # This is a copy of MangeClubPage until I know a better way
        # of redirecting        
        members = []
        if len(club.members) > 0:
            members = db.get(club.members)
        template_values = {
            'club' : club,
            'members' : members
        }
        path = os.path.join(os.path.dirname(__file__), 'manage_club.html')
        self.response.out.write(template.render(path, template_values))

class SendReminder(webapp.RequestHandler):
    def post(self):
        key = cgi.escape(self.request.get('id'))
        club = db.get(key)
        duty_key = cgi.escape(self.request.get('duty_id'))
        duty = db.get(duty_key)
        # Send an email reminder.
        mail.send_mail(users.get_current_user().email(),
                       duty.email,
                       "Donut-Duty Reminder",
                       "This is a reminder that you have donut-duty.")
        # Display the manage_club page
        members = []
        if len(club.members) > 0:
            members = db.get(club.members)
        template_values = {
            'club' : club,
            'members' : members
        }
        path = os.path.join(os.path.dirname(__file__), 'manage_club.html')
        self.response.out.write(template.render(path, template_values))

class ListPage(webapp.RequestHandler):
    def get(self):
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'list.html')
        self.response.out.write(template.render(path, template_values))


class EditPage(webapp.RequestHandler):
    def get(self):
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'edit.html')
        self.response.out.write(template.render(path, template_values))


class SendPage(webapp.RequestHandler):
    def get(self):
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'send.html')
        self.response.out.write(template.render(path, template_values))


def main():
    application = webapp.WSGIApplication([('/', IndexPage),
                                          ('/clubs', ClubsPage),
                                          ('/create_club', CreateClubPage),
                                          ('/manage_club', ManageClubPage),
                                          ('/edit_members', EditMembersPage),
                                          ('/save_member_list', SaveMemberList),
                                          ('/send_reminder', SendReminder),
                                          ('/list', ListPage),
                                          ('/edit', EditPage),
                                          ('/send', SendPage)], debug=True)
    wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
    main()

